import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '@/pages/Index'
import Login from '@/pages/Login'
import AddGoods from '@/pages/AddGoods'
import GoodsList from '@/pages/GoodsList'
import CartList from '@/pages/CartList'

import FilmList from '@/pages/FilmList'
import Details from '@/pages/Details'
Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Index,
      meta: {
        title: '首页',
      },
      children: [
        {
          path: '/',
          component: AddGoods,
          meta: {
            title: '添加商品',
          },
        },
        {
          path: '/goodsList',
          component: GoodsList,
          meta: {
            title: '商品列表',
          },
        },
        {
          path: '/cartList',
          component: CartList,
          meta: {
            //权限验证
            isAuthor: true,
            title: '购物车列表',
          },
        },
      ],
    },
    {
      path: '/login',
      component: Login,
      meta: {
        title: '登录',
      },
    },
    {
      path: '/filmList',
      component: FilmList,
      meta: {
        title: '电影列表',
      },
      children: [
        {
          path: '/filmList/:filmId',
          component: Details,
        },
      ],
    },
  ],
  mode: 'history',
  // 高亮的样式
  linkActiveClass: 'active',
})
// 全局前置守卫
//to：到哪
//from:从哪来
//next：放行
router.beforeEach(function (to, from, next) {
  // 判断是否要进行权限
  if (to.meta.isAuthor) {
    // 已经登录那么放行
    if (localStorage.getItem('token')) next()
    // 已经登录跳转至登录页
    else next({ path: '/login', query: { cb: to.path } })
  } else next()
})
// 全局后置守卫:在beforeRouteEnter之后以及beforeCreate之前执行
router.afterEach(function (to, from, next) {
  document.title = to.meta.title
})
export default router
